package com.lw.extraceim.ui.activity.customer;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.lw.extraceim.R;
import com.lw.extraceim.app.AppConstants;
import com.lw.extraceim.loader.CustomerLoader;
import com.lw.extraceim.model.CustomerInfo;
import com.lw.extraceim.model.UserInfo;
import com.lw.extraceim.net.HttpResponseParam;
import com.lw.extraceim.net.ResponseCode;
import com.lw.extraceim.net.callback.HttpResponseParamCallback;
import com.lw.extraceim.ui.activity.base.BaseActivity;
import com.lw.extraceim.ui.activity.es.WriteExpressSheetActivity;
import com.lw.extraceim.util.JsonUtils;
import com.lw.extraceim.util.TextUtil;
import com.lw.extraceim.view.ExtraceToolbar;

import org.json.JSONException;

import java.net.Inet4Address;

import okhttp3.Call;

/**
 * @Author : liwei
 * @Email : 1759840027@qq.com
 * @Description : 客户信息编辑页面
 * @Date : 2019/4/14 8:42
 */
public class CustomerEditActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "CustomerEditActivity";

    private int resultCode = CUSTOMER_EDIT_ACTIVITY_CODE;

    private boolean isForResult = false;

    private ExtraceToolbar mToolbar;

//    private ImageButton mBtnBack;//返回按钮
//    private TextView mTvTitle;//界面标题
//    private Button mButtonSave;//保存
    private EditText mEtCustomerName;//客户姓名
    private EditText mEtCustomerPhone;//客户电话号码
    private EditText mEtCustomerLocation;//省市区
    private EditText mEtCustomerDetaiAddress;//详细地址
    private EditText mEtPostCode;//邮编
    private CustomerInfo customerInfo;
//    private String action;

    private CityPickerView mCityPickerView;//城市选择器
    private String defaultProvinceName = "河南省";
    private String defaultCityName = "郑州市";
    private String defaultDistrict = "高新区";



    private int action = ADD_ACTION;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_customer_edit);
        //初始化CityPicker
        mCityPickerView = new CityPickerView();
        mCityPickerView.init(this);

        mToolbar = findViewById(R.id.toolbar);
        initToolBar();
        mEtCustomerName = findViewById(R.id.et_customer_name);
        mEtCustomerPhone = findViewById(R.id.et_customer_phone);
        mEtCustomerLocation = findViewById(R.id.et_customer_location);
        mEtCustomerLocation.setFocusable(false);//让EditText失去焦点，然后获取点击事件
        mEtCustomerDetaiAddress = findViewById(R.id.et_customer_detailed_address);
        mEtPostCode = findViewById(R.id.et_post_code);
    }

    protected void initToolBar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mToolbar.setBackButtonOnClickListerner(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CustomerEditActivity.this.finish();
            }
        });
        mToolbar.setTitle("编辑客户");
        mToolbar.setButtonOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: 执行save方法");
                save();
            }
        });
    }
    @Override
    public void initData() {
        Intent intent = getIntent();
        customerInfo = (CustomerInfo) intent.getSerializableExtra("customerInfo");
        Log.d(TAG, "initData: " + customerInfo);

        isForResult = intent.getBooleanExtra("forResult", false);
        action = intent.getIntExtra("action", ADD_ACTION); //默认为添加客户信息
        if (isForResult) {
            resultCode = intent.getIntExtra("resultCode", CUSTOMER_EDIT_ACTIVITY_CODE);
        }

        if (customerInfo != null) {
            load();
        }

    }

    @Override
    public void initEvent() {
//        mBtnBack.setOnClickListener(this);
        mEtCustomerLocation.setOnClickListener(this);
//        mButtonSave.setOnClickListener(this);
    }


    @Override
    public void refreshUI() {
        refreshTitle();
        refreshCustomer();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.et_customer_location: {
                BaseActivity.hideSoftKeyboard(this);
                showCityPicker();
            }
        }
    }

    /**
     * 刷新客户信息
     */
    public void refreshCustomer() {
        if (customerInfo != null) {
            Log.d(TAG, "refreshCustomer: "  + customerInfo);
            mEtCustomerName.setText(customerInfo.getName());
            mEtCustomerPhone.setText(customerInfo.getTelCode());
            mEtCustomerLocation.setText(customerInfo.getRegionString());
            Log.d(TAG, "refreshCustomer: " + customerInfo.getRegionString());
            mEtCustomerLocation.setTag(customerInfo.getRegionCode());
            mEtCustomerDetaiAddress.setText(customerInfo.getAddress());
            mEtPostCode.setText(customerInfo.getPostCode() + " ");
        }
    }

    public static final int ADD_ACTION = 0;//表示添加客户信息
    public static final int EDIT_ACTION = 1;//编辑客户信息
    public static final int EDIT_SENDER = 2;//编辑收件人
    public static final int EDIT_RECIVER = 3;//编辑寄件人
    public final static int CUSTOMER_EDIT_ACTIVITY_CODE = 100;//客户编辑
    public final static int CUSTOMER_EDIT_SENDER_RESULT_CODE = 101;//编辑寄件人信息
    public final static int CUSTOMER_EDIT_RECIVERE_RESULT_CODE = 102;//编辑收件人信息
    /**
     * 刷新界面标题
     */
    public void refreshTitle() {
        switch (action) {
            case ADD_ACTION: {
                mToolbar.setTitleText("新建客户");
                resultCode = CUSTOMER_EDIT_ACTIVITY_CODE;
                break;
            }
            case EDIT_SENDER: {
                mToolbar.setTitleText("编辑寄件人");
                resultCode = CUSTOMER_EDIT_SENDER_RESULT_CODE;
                break;
            }
            case EDIT_RECIVER: {
                mToolbar.setTitleText("编辑收件人");
                resultCode = CUSTOMER_EDIT_RECIVERE_RESULT_CODE;
                break;
            }
            case EDIT_ACTION: {
                mToolbar.setTitleText("编辑客户信息");
                resultCode = CUSTOMER_EDIT_ACTIVITY_CODE;
                break;
            }
        }


    }

    /**
     * 检查输入是否正确
     *
     * @return
     */
    public boolean checkInput() {
        customerInfo = (customerInfo == null ? new CustomerInfo() : customerInfo);
        customerInfo.setName(mEtCustomerName.getText().toString().trim());
        if (TextUtil.isNull(customerInfo.getName())) {
            alert("姓名不能为空");
            return false;
        }
        customerInfo.setTelCode(mEtCustomerPhone.getText().toString().trim());
        if (TextUtil.isNull(customerInfo.getTelCode())) {
            alert("电话号码不能为空");
            return false;
        } else if (!TextUtil.isPhone(customerInfo.getTelCode())) {
            alert("电话号码格式错误");
            return false;
        }

        customerInfo.setRegionString(mEtCustomerLocation.getText().toString().trim());
        if (TextUtil.isNull(customerInfo.getRegionString())) {
            alert("省市区不能为空");
            return false;
        }

        customerInfo.setAddress(mEtCustomerDetaiAddress.getText().toString().trim());
        if (TextUtil.isNull(customerInfo.getAddress())) {
            alert("详细地址不能为空");
            return false;
        }

        customerInfo.setRegionCode((String) mEtCustomerLocation.getTag());
        Log.d(TAG, "checkInput: " + mEtCustomerLocation.getTag());

        try {
            customerInfo.setPostCode(Integer.parseInt(mEtPostCode.getText().toString().trim()));
        } catch (NumberFormatException e) {
            e.printStackTrace();
            alert("邮编格式错误");
            return false;
        }

        return true;
    }

    private final CustomerLoader customerLoader = new CustomerLoader(this);


    private HttpResponseParamCallback callback = new HttpResponseParamCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            alert("网络错误" + e.getMessage());
            Log.d(TAG, "onError: 网络错误" + e.getMessage());
        }
        @Override
        public void onResponse(HttpResponseParam response, int id) {
            if (response.code.getCode() == ResponseCode.SUCESS) {
                try {
                    customerInfo = JsonUtils.fromJson(response.reseponseJson.getJSONObject("customer").toString(), new TypeToken<CustomerInfo>() {
                    });
                    if (customerInfo != null) {
                        customerInfo.onSave();

                        Log.d(TAG, "onResponse: " + customerInfo);
                        toast("保存成功");
                        if (isForResult && isBack) {
                            //数据是使用Intent返回
                            Intent intent = new Intent();
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("customerInfo", customerInfo);
                            intent.putExtras(bundle);
                            //设置返回数据
                            CustomerEditActivity.this.setResult(resultCode, intent);
                            //关闭Activity
                            CustomerEditActivity.this.finish();
                        }else{
                            refreshUI();
                        }
                    } else {
                        alert(response.code.getMessage());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.d(TAG, "onResponse: 数据格式错误" + response.reseponseJson);
                }
            } else {
                alert(response.code.getMessage());
            }
        }
    };

    private boolean isBack = false;
    /**
     * 保存客户信息
     */
    public void save() {
        if (checkInput()) {
            isBack = isForResult;
            if(customerInfo.isSaved()){
                update();
            }else {
                customerLoader.save(customerInfo, callback);
            }
        }
    }

    /**
     * 加载客户信息
     */
    public void load() {
        if (customerInfo != null && customerInfo.getId() != 0) {
            customerLoader.get(customerInfo.getId(), callback);
        }
    }

    /**
     * 修改客户信息
     */
    public void update(){
        if(customerInfo != null && customerInfo.getId() != 0 && customerInfo.isSaved()){
            customerLoader.update(customerInfo,callback);
        }
    }

    /**
     * 获取customerInfo
     *
     * @param customerInfoId
     * @return
     */
    public CustomerInfo load(int customerInfoId) {
        return null;
    }


    @Override
    public void onBackPressed() {
        super.finish();
    }

    /**
     * 显示城市选择器
     */
    public void showCityPicker() {
        CityConfig cityConfig = new CityConfig.Builder()
                .title("选择城市")//标题
                .titleTextSize(18)//标题文字大小
                .titleTextColor("#585858")//标题文字颜  色
                .titleBackgroundColor("#E9E9E9")//标题栏背景色
                .confirTextColor("#585858")//确认按钮文字颜色
                .confirmText("确认")//确认按钮文字
                .confirmTextSize(16)//确认按钮文字大小
                .cancelTextColor("#585858")//取消按钮文字颜色
                .cancelText("取消")//取消按钮文字
                .cancelTextSize(16)//取消按钮文字大小
                .setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)//显示类，只显示省份一级，显示省市两级还是显示省市区三级
                .showBackground(true)//是否显示半透明背景
                .visibleItemsCount(5)//显示item的数量
                .province(defaultProvinceName)//默认显示的省份
                .city(defaultCityName)//默认显示省份下面的城市
                .district(defaultDistrict)//默认显示省市下面的区县数据
                .provinceCyclic(true)//省份滚轮是否可以循环滚动
                .cityCyclic(true)//城市滚轮是否可以循环滚动
                .districtCyclic(true)//区县滚轮是否循环滚动
                .setCustomItemLayout(R.layout.item_city)//自定义item的布局
                .setCustomItemTextViewId(R.id.item_city_name_tv)//自定义item布局里面的textViewid
                .drawShadows(true)//滚轮不显示模糊效果
                .setLineColor("#03a9f4")//中间横线的颜色
                .setLineHeigh(5)//中间横线的高度
                .setShowGAT(false)//是否显示港澳台数据，默认不显示
                .build();

        mCityPickerView.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                mEtCustomerLocation.setText(province.getName() + " " + city.getName() + " " + district.getName());
                mEtCustomerLocation.setTag(district.getId());
            }

            @Override
            public void onCancel() {
                toast("已取消");
            }
        });
        //设置自定义的属性配置
        mCityPickerView.setConfig(cityConfig);
        mCityPickerView.showCityPicker();
    }


    /**
     * 启动当前Activity
     *
     * @param context
     * @param action
     * @param customerInfo
     */
    public static void actionStart(@NonNull Context context, @NonNull int action, CustomerInfo customerInfo) {
        Intent intent = new Intent(context, CustomerEditActivity.class);
        if (customerInfo != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("customerInfo", customerInfo);
            intent.putExtras(bundle);
        }
        intent.putExtra("action", action);
        context.startActivity(intent);
    }


    /**
     * 启动当前ActivityForResult
     * @param context
     * @param action
     * @param customerInfo
     */
    public static void actionStartForResult(@NonNull Activity context, int action, CustomerInfo customerInfo) {
        Intent intent = new Intent(context, CustomerEditActivity.class);
        if (customerInfo != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("customerInfo", customerInfo);
            intent.putExtras(bundle);
        }
        intent.putExtra("forResult", true);
        intent.putExtra("action", action);
        context.startActivityForResult(intent, CUSTOMER_EDIT_ACTIVITY_CODE);
    }
}
